package tech.minesoft.utils;

import cn.hutool.core.io.file.FileWriter;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@Slf4j
public class ConfigUtils {
    private static Path configFile;
    private static ConfigVal configVal;

    static {
        initFile();
    }

    private static void initFile() {
        try {
            String userHome = System.getProperty("user.home");
            Path parent = Paths.get(userHome, ".minesoft");
            if (Files.notExists(parent)) {
                Files.createDirectory(parent);
            }

            configFile = parent.resolve("minetools.json");
            if (Files.notExists(configFile)) {
                Files.createFile(configFile);
                configVal = ConfigVal.initConfig();
                writeConfig();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        readConfig();
    }

    private static void readConfig() {
        JSONObject json = JSONUtil.readJSONObject(configFile.toFile(), StandardCharsets.UTF_8);
        configVal = json.toBean(ConfigVal.class);
    }

    private static void writeConfig() {
        FileWriter writer = new FileWriter(configFile.toFile());
        JSONObject json = new JSONObject(configVal);
        writer.write(json.toStringPretty());
    }

    public static ConfigVal getConfig() {
        return configVal;
    }
}
